#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2021/7/25 12:26
# @Author : cjw
from sqlalchemy.orm import Session

from app.models.user import User
from app.db.session import create_table, drop_table
from app.models.user import User
from app.models.item import Item
from app.models.news import News
from app.utils.generate_data import GenerateData
from app.core.security import get_password_hash
from app.api.utils.db import get_db


def add_user_item(item_num: int = 2, db: Session = next(get_db())):
    """
    创建用户和项目
    :param item_num: 
    :param db: 
    :return: 
    """""
    gd = GenerateData()
    user = User(
        full_name=gd.name(),
        email=gd.email(),
        hashed_password=get_password_hash('123456')
    )
    for i in range(item_num):
        user.items.append(
            Item(
                title=gd.word(),
                description=gd.word(),
                owner=user
            )
        )

    # 开启事务，提交更新
    db.begin()
    try:
        db.add(user)
    except Exception as e:
        db.rollback()
        raise e
    else:
        db.commit()


if __name__ == '__main__':
    create_table()
